package com.javasm.mingming.common.interceptor;

import com.javasm.mingming.common.annotation.Auth;
import com.javasm.mingming.common.exception.JavasmException;
import com.javasm.mingming.common.exception.JavasmExceptionEnum;
import com.javasm.mingming.common.utils.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author javasm
 * @version 0.1
 * @className LoginInterceptor
 * @descriptioin:
 * @date 2025/1/8 11:18
 * @since jdk11
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //获取 被访问的方法对象
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //获取 自定义注解
        Auth annotation = method.getAnnotation(Auth.class);
        if (annotation == null){
            //不加密
            return true;
        }
        //加密的请求
        String token = request.getHeader(TokenUtil.Server_Token_Key);
        if (StringUtils.isEmpty(token)){
            //当前的方法,需要加密访问,但是,没有传token
            throw new JavasmException(JavasmExceptionEnum.PermissionDenied);
        }
        String uid = TokenUtil.parse(token);
        return true;
    }
}
